package com.house.service;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.house.dao.DictMapper;
import com.house.entity.Dict;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 字典模块服务层
 */
@Service
@Slf4j
public class DictService extends ServiceImpl<DictMapper, Dict> {

    /**
     * 初始化字典MAP 程序启动时执行
     */
    public static Map<String, List<Dict>> DICE_MAP = new HashMap();

    @PostConstruct
    public void init() {
        list().forEach(dict -> {
            if (DICE_MAP.containsKey(dict.getCode())) {
                DICE_MAP.get(dict.getCode()).add(dict);
            } else {
                List<Dict> dices = new ArrayList<>();
                dices.add(dict);
                DICE_MAP.put(dict.getCode(), dices);
            }
        });
    }


    /**
     * 获取字典文本
     * @param code
     * @param value
     * @return
     */
    public String getText(String code, String value) {
        for(Dict dict : DICE_MAP.get(code)) {
            if(value.equals(dict.getValue())) {
                return dict.getText();
            }
        }

        return value;
    }
}
